import koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import cors from '@koa/cors'
import { Sequelize,DataTypes,Op } from 'sequelize'
let app = new koa()
let router=new Router()
 const sequelize=new Sequelize('db1','root','123456',{
    dialect:'mysql',
    host:'localhost'
})
const Book=sequelize.define('book',{
    bookName:DataTypes.STRING,
    author:DataTypes.STRING
})

//  Book.bulkCreate(
//     {
//         bookName:123,
//         author:234
//     },
//     {
//         bookName:123,
//         author:234
//     },
//     {
//         bookName:123,
//         author:234
//     },
//     {
//         bookName:123,
//         author:234
//     })

// await sequelize.sync()

router.get('/books',async(ctx)=>{
    let books=await Book.findAll()
    ctx.body={
        code:1000,
        data:books,
        msg:'列表成功'
    }
})
router.post('/books',async(ctx)=>{
    let obj=ctx.request.body
    let res=await Book.create(obj)
    ctx.body={
        code:1000,
        data:res,
        msg:'新增成功'
    }
})
router.put('/books/:id',async(ctx)=>{
    let id=ctx.params.id
    let obj=ctx.request.body
    let res=await Book.update(obj,{
        where:{
            id:id
        }
    })
    ctx.body={
        code:1000,
        data:res,
        msg:'修改成功'
    }
})
router.delete('/books/:id',async(ctx)=>{
    let id= ctx.params.id || 0
    let res= await Book.destroy({
        where:{
            id
        }
    })
    ctx.body={
        code:1000,
        data:res,
        msg:'删除成功'
    }
})
router.get('/books/:id',async(ctx)=>{
    let id=ctx.params.id || 0
    let books= await Book.findByPk(id)
    ctx.body={
        code:1000,
        data:books,
        msg:'列表成功'
    }
})
app.use(cors())
app.use(bodyParser())
app.use(router.routes())
let appPort=8000
app.listen(appPort)
console.log(`http://localhost:${appPort}`);
